package dao

import (
	"log"
	"testhttp/datasource"
	"testhttp/model"
)

func ListOrder(searchparams string, pagesize, page int) ([]model.Orders, int64) {
	uniq := new(model.Orders)
	res := make([]model.Orders, 0)
	offset := (page - 1) * pagesize

	// if goods == "" && shop == "" {
	count, errcount := datasource.InstanceMaster().Where(searchparams).Count(uniq)
	if errcount != nil {
		log.Print("Error ListOrders()count:", errcount)
	}

	err := datasource.InstanceMaster().Where(searchparams).Limit(pagesize, offset).Find(&res)
	if err != nil {
		log.Print("Error ListOrders()find:", err)
	}

	return res, count
}

func InsertOrders(data []model.Orders) int64 {
	affected, err := datasource.InstanceMaster().Insert(data)
	log.Printf("Success! %d records insert.\n", affected)
	if err != nil {
		log.Print("Error InsertOrders():", err)
	}
	return affected
}

func UpdateOrders(data []model.Orders) (int, int) {
	var sum_err int
	var success int
	for x := 0; x < len(data); x++ {
		// log.Print("Debug uid:", dealer[x].id)
		affected, err := datasource.InstanceMaster().Where("id=?", data[x].Id).Update(data[x])

		if err != nil {
			log.Print("Error UpdateOrders():", err)
			sum_err++
		} else {
			log.Printf("%d records updated.\n", affected)
			success++
		}

	}
	return success, sum_err
}
